'use strict'
var http = require('http');
var https = require('https');
var fs = require('fs');

var express = require('express');
var serveIndex = require('serve-index');
var { Server } = require('socket.io');

var log4j = require('log4js');
const e = require('express');
log4j.configure({
    appenders: {
        out: { type: 'console' },
        app: { type: 'file', filename: 'log.log' }
    },
    categories: {
        default: { appenders: ['out', 'app'], level: 'debug' }
    }
});
var logger = log4j.getLogger();

var app = express();
app.use(serveIndex('./public'));
app.use(express.static('./public'));

var http_server = http.createServer(app);
http_server.listen(80,'0.0.0.0');

var https_server = https.createServer({
    key: fs.readFileSync('cert.key'),
    cert: fs.readFileSync('cert.crt') 
}, app);
const io = new Server(https_server); 
https_server.listen(443,'0.0.0.0');

var MaxConnectCount = 2;
io.on('connection', function(socket){
    logger.log('a user connected');

    socket.on('message', (room, data)=>{//服务器中转消息
        socket.to(room).emit('message', room, data)
	});
    
   socket.on("join",(room,isReconnect)=>{
    logger.log('a user join :'+ room);
    socket.join(room);
    if(isReconnect){ 
        logger.log("断开重连操作");
        return;
    };

    const rooms = io.sockets.adapter.rooms 
    

    var myRoom = rooms.get(room);
    if(myRoom){ 
        //set 长度
        var users = myRoom.size;
        if(users <= MaxConnectCount){
            socket.emit("joined",room,socket.id);
            if(users > 1){
                socket.to(room).emit("otherjoin",room,socket.id);
                logger.log('emit other join');
            }
        }else{
            logger.log('the room is full');
            socket.leave(room);
            socket.emit("full",room,socket.id);
        }
        logger.log('the number of users in the room is:'+users);
        //socket.emit("joined",room,socket.id);//给自己回
        // socket.to(room).emit("joined", room,socket.id);
        // socket.broadcast.emit("joined",room,socket.id);//除了自己，所有人
        // io.in(room).emit("joined", room,socket.id);//房间内所有人
    }else{
        socket.emit("message", room, "11", "no room");
        logger.log('a user join but no room');
    }
   })
   socket.on("leave",(room)=>{
    logger.log('a user leave :'+ room);
    
    var myRoom = io.sockets.adapter.rooms.get(room);
    if(myRoom){
        var users = myRoom.size;
        logger.log('the number of users in the room is:'+users);
        socket.to(room).emit("bye",room,socket.id);//向其他人发送bye
        socket.emit("leaved",room,socket.id);//向自己发送leaved
    }else{
        logger.log("no room");
    }
    socket.leave(room);
   })

   socket.on('disconnect', function(){
    logger.log('user disconnected');
   });

});

logger.log("111");